<template>
    <div class="page-account">
        <div v-if="" class="page-account-header">
            <i-header-i18n />
        </div>
        <div class="page-account-container">
            <div class="page-account-top">
                <div class="page-account-top-logo">
                    <img src="@/assets/images/register_logo.png" alt="logo">
                </div>
                <div class="page-account-top-desc mt10">吾心及宇宙，天下若尘微</div>
                <div class="page-account-top-desc mt10">勤记录，懂分享</div>
            </div>
            <Login ref="form" @on-submit="handleSubmit">
                <Poptip trigger="focus" placement="right" width="240">
                    <UserName name="account" :rules="accountRule" :maxlength="50" @on-change="handleChangeAccount" />
                    <div slot="content" class="page-account-register-tip">
                        <div class="page-account-register-tip-title" >
                            查重结果：
                            <span v-if="checkUserName === 1">可以使用</span>
                            <span v-if="checkUserName === 2">此账号已存在</span>
                        </div>
                        <div class="page-account-register-tip-desc">
                            请输入由纯中文或纯英文组成的用户名。用户名不宜过长或过短。
                        </div>
                    </div>
                </Poptip>
                <Poptip trigger="focus" placement="right" width="240">
                    <Password name="password" :rules="passwordRule" :maxlength="50" placeholder="至少6位密码，区分大小写" @on-change="handleChangePassword" />
                    <div slot="content" class="page-account-register-tip">
                        <div class="page-account-register-tip-title" :class="passwordTip.class">
                            强度：{{ passwordTip.strong }}
                        </div>
                        <Progress :percent="passwordTip.percent" hide-info :stroke-width="6" :stroke-color="passwordTip.color" />
                        <div class="page-account-register-tip-desc">
                            请至少输入 6 个字符。请不要使用容易被猜到的密码。
                        </div>
                    </div>
                </Poptip>
                <Password name="passwordConfirm" :rules="passwordConfirmRule" :maxlength="50" placeholder="确认密码" />
                <Poptip trigger="focus" placement="right" width="240">
                    <Email name="mail" @on-change="handleChangeEmail" />
                    <div slot="content" class="page-account-register-tip">
                        <div class="page-account-register-tip-title" >
                            查重结果：
                            <span v-if="checkEmail === 1">可以使用</span>
                            <span v-if="checkEmail === 2">邮箱已注册</span>
                        </div>
                    </div>
                </Poptip>
                <Captcha name="captcha" :field="['mail']" enter-to-submit @on-get-captcha="handleGetCaptcha" />
                <Submit>{{ $t('page.register.submit') }}</Submit>
            </Login>
            <div class="page-account-to-login">
                <router-link :to="{ name: 'login' }">{{ $t('page.register.other') }}</router-link>
            </div>
        </div>
        <i-copyright />
    </div>
</template>
<script>
    import { accountRegister, SendCodeApi, CheckUserName, CheckEmail  } from '@/api/account'
    import iCopyright from '@/components/copyright';
    import { mapActions } from 'vuex';
    import mixins from '../mixins';

    export default {
        mixins: [ mixins ],
        components: { iCopyright },
        data () {
            // 二次校验密码
            // 因为 iView Pro 的表单控件省去了对数据的绑定，因此需要通过 ref 从 Login 组件中获取数据
            // 下面的 formValidate.password 中的 password，指的是给 <Password> 组件设置的 name="password"
            const validatePassCheck = (rule, value, callback) => {
                if (value !== this.$refs.form.formValidate.password) {
                    callback(new Error('两次输入的密码不匹配！'))
                } else {
                    callback()
                }
            };
            const validateAccountCheck = (rule, value, callback) => {
                var chinese = new RegExp("^[\u4E00-\u9FA5]+$")
                var english = new RegExp("^[A-Za-z]+$")
                if(!chinese.test(value) && !english.test(value)) {
                    callback(new Error('请输入由纯中文或纯英文组成的用户名！'))
                }
                if(chinese.test(value)) {
                    let chineseLen = value.replace(/[\u0391-\uFFE5]/g,"aa").length
                    if(chineseLen < 4 || chineseLen > 20)
                        callback(new Error('中文用户名长度应为 2 至 10 个字之间！'))
                }
                if(english.test(value)) {
                    let englishLen = value.length
                    if(englishLen < 4 || englishLen > 20)
                        callback(new Error('英文用户名长度应为 4 至 20 个字之间！'))
                }
                callback()
            };

            return {
                passwordRule: [
                    {
                        required: true, message: '密码不能为空！', trigger: 'change'
                    },
                    {
                        min: 6, message: '密码不能少于6位！', trigger: 'change'
                    }
                ],
                passwordConfirmRule: [
                    {
                        required: true, message: '确认密码不能为空！', trigger: 'change'
                    },
                    { validator: validatePassCheck, trigger: 'change' }
                ],
                accountRule: [
                    {
                        required: true, message: '用户名不能为空！', trigger: 'change'
                    },
                    { validator: validateAccountCheck, trigger: 'change' }
                ],
                // 密码长度，在密码强度提示时作为判断依据
                passwordLen: 0,

                editTime: 0,

                checkUserName: 0,
                checkEmail: 0,
            }
        },
        computed: {
            // 密码强度提示文案等
            passwordTip () {
                let strong = '强';
                let className = 'strong';
                let percent = this.passwordLen > 10 ? 10 : this.passwordLen;
                let color = '#19be6b';

                if (this.passwordLen < 6) {
                    strong = '太短';
                    className = 'low';
                    color = '#ed4014';
                } else if (this.passwordLen < 10) {
                    strong = '中';
                    className = 'medium';
                    color = '#ff9900';
                }

                return {
                    strong,
                    class: `page-account-register-tip-${className}`,
                    percent: percent * 10,
                    color
                }
            }
        },
        methods: {
            ...mapActions('admin/account', [
                'register',
                'login'
            ]),
            handleChangePassword (val) {
                this.passwordLen = val.length;
            },
            handleChangeAccount (val) {
                clearTimeout(this.editTime)
                this.editTime = setTimeout( () => { this.CheckUserName(val) }, 500)
            },
            handleChangeEmail (val) {
                clearTimeout(this.editTime)
                this.editTime = setTimeout( () => { this.CheckEmail(val) }, 500)
            },
            CheckUserName(val) {
                CheckUserName({account: val}).then(async res => {
                    if (res.data) {
                        this.checkUserName = 1
                    } else {
                        this.checkUserName = 2
                    }
                }).catch(res => {
                    this.$Message.error(res.msg);
                })
            },
            CheckEmail(val) {
                CheckEmail({email: val}).then(async res => {
                    if (res.data) {
                        this.checkEmail = 1
                    } else {
                        this.checkEmail = 2
                    }
                }).catch(res => {
                    this.$Message.error(res.msg);
                })
            },
            /**
             * @description 注册
             * 表单校验已有 iView Pro 自动完成，如有需要修改，请阅读 iView Pro 文档
             */
            handleSubmit (valid, values) {
                if (valid) {
                    const { account, password, mail, captcha } = values;
                    accountRegister({
                        account,
                        password,
                        mail,
                        captcha
                    }).then(async res => {
                        if (res.status === 200) {
                            this.$Notice.success({title: '注册成功'})
                            this.$router.push({ path: '/admin/login' })
                        } else {
                            this.$Message.error({
                                content: res.msg,
                                background: true,
                                duration: 5,
                                closable: true,
                            })
                        }
                    }).catch(res => {
                        this.$Message.error(res.msg);
                    })
                }
            },
            /**
             * @description 获取验证码
             * */
            handleGetCaptcha (valid, values) {
                SendCodeApi({mail: values.mail}).then(async res => {
                    if (res.status === 200) {
                        this.$Notice.success({title: '发送成功'})
                    } else {
                        this.$Message.error({
                            content: res.msg,
                            background: true,
                            duration: 5,
                            closable: true,
                        })
                    }
                }).catch(res => {
                    this.$Message.error(res.msg);
                })
            }
        }
    };
</script>
